/*
 * @Author: 肖思汗 
 * @Date: 2025-06-30 19:49:17 
 * @Last Modified by: 肖思汗
 * @Last Modified time: 2025-07-10 16:37:34
 */

import { useContext } from 'react';
import { useEffect, useRef, useState } from "react";
import { childreContolsContext } from './MyScrollViewContext';

interface MyScrollViewItemProps extends React.HTMLAttributes<HTMLDivElement> {
    index: number;
}

export default function MyScrollViewItem(props: MyScrollViewItemProps) {

    // 是否显示子元素，默认为 true
    const showChildren = useRef<boolean>(true);

    // 是否显示子元素
    const [show, setShow] = useState<boolean>(true);

    const [size, setViewSize] = useState<{ width: number, height: number }>({ width: 0, height: 0 });

    const ViewRef = useRef<HTMLDivElement>(null);

    let { children, style, ...otherProps } = props;

    if (!(show || showChildren.current)) {
        style = Object.assign({}, style, { ...size, overflow: 'hidden' });
    } else {
        style = Object.assign({}, style, { overflow: 'hidden' });
    }

    useEffect(() => {
        (async () => {
            await new Promise(resolve => requestAnimationFrame(resolve));
            await new Promise(resolve => requestAnimationFrame(resolve));
            await new Promise(resolve => requestAnimationFrame(resolve));
            if (ViewRef.current && (show || showChildren.current)) {
                const rect = await ViewRef.current.getBoundingClientRect();
                if (rect) {
                    showChildren.current = false;
                    setViewSize({
                        width: rect.width,
                        height: rect.height
                    });
                }
            }
        })();
    }, [show]);

    const childreContols = useContext(childreContolsContext);
    childreContols[props.index].height = size.height;
    childreContols[props.index].isVisible = (_show: boolean) => {
        if (_show !== show) {
            showChildren.current = true;
            setShow(_show);
        }
        // console.log(props.index, _show, show);
    }

    // console.log(props.index, "show", show, "showChildren.current", showChildren.current);

    return (
        <div
            ref={ViewRef}
            {...otherProps}
            style={style}
        >
            {(show || showChildren.current) ? children : null}
        </div>
    );
}